package cn.imvc.app.models;


import java.util.Collection;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.DealerLevel;
import cn.imvc.app.repositories.DealerLevelRepository;
import cn.imvc.data.domain.ViewRequest;

@Service
public class DealerLevelModelImpl implements DealerLevelModel{
	
	@Autowired
	private DealerLevelRepository dealerLevelRepository;
	
	
	
	public DealerLevel get(int id){
		return dealerLevelRepository.findOne(id);
	}
	
	
	public Page<DealerLevel> find(ViewRequest viewRequest) {
		return (Page<DealerLevel>) dealerLevelRepository.findAll();
	}

	public DealerLevel save(DealerLevel dealerLevel) {
		
		DealerLevel dealerLevel2 = dealerLevelRepository.saveAndFlush(dealerLevel);
		
		
		return dealerLevel2;
	}
	public DealerLevel update(DealerLevel newDealerLevel) {
		DealerLevel loadDealerLevel=get(newDealerLevel.getId());
		BeanUtils.copyProperties(newDealerLevel, loadDealerLevel, new String[]{"id"});
		
		return dealerLevelRepository.saveAndFlush(loadDealerLevel);
	}
	public void delete(int id) {
		dealerLevelRepository.delete(id);
		
	}
	public void deleteBatch(int[] ids) {

		for (int id : ids) {
			delete(id);
		}
		
	}
	
	public List<DealerLevel> findByLevelGreaterThan (int level){
		return dealerLevelRepository.findByTypeNotAndLevelGreaterThanOrderByLevel((byte)2,level);
	}
	public List<DealerLevel> findAll(){
		return dealerLevelRepository.findByOrderByLevelAsc();
	}
	public List<Object[]> findMaxLevel(){
		return dealerLevelRepository.findAllSql("select max(level) from dealer_level"); 
	}
	
	public DealerLevel findMinDealerLevel(){
		List<DealerLevel> list = dealerLevelRepository.findByOrderByLevelAsc();
		return list.get(0);
	}
	
	public DealerLevel findByLevel(int level){
		List<DealerLevel> list = dealerLevelRepository.findByLevel(level);
		if(list != null && list.size() > 0){
			return list.get(0);
		} else {
			return null;
		}
	}

}
